<template>
  <div style="width:100%;height:500px;border:1px solid black';position:relative">
    <div
      id="myBlueDiv"
      style="width:350px;height:200px;position:absolute;top:0;right:0;bottom:0;left:0;margin:auto;"
    >
      <el-form ref="loginForm" :rules="logingRules" :model="loginForm" style="text-align:center">
        <el-form-item prop="username">
          <span>
            <i class="el-icon-s-custom"></i>
          </span>
          <el-input placeholder="用户名" v-model="loginForm.username" style="width:300px"></el-input>
        </el-form-item>
        <el-form-item prop="userpassword">
          <span class="svg-container">
            <i class="el-icon-s-ticket"></i>
          </span>
          <el-tooltip content="不小于8位,包含数字和字母" placement="right" manaual>
            <el-input placeholder="密码" v-model="loginForm.userpassword" style="width:300px"></el-input>
          </el-tooltip>
        </el-form-item>
        <el-button style="align" @click="handleLogin()">登录</el-button>
        <el-button style="align" @click="testVuex()">注册</el-button>
      </el-form>
    </div>
  </div>
</template>

  <script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import { tpost,post } from "../request";
import jwt from "jsonwebtoken";
export default {
  data() {
    return {
      title: "登录界面",
      errmsg: "",
      loginForm: {
        username: "admin",
        userpassword: "userpassword"
      },
      logingRules: {
        username: [
          { required: true, trigger: "blur", validator: this.validateUsername }
        ],
        userpassword: [
          {
            required: true,
            trigger: "blur",
            validator: this.validateUserpassword
          }
        ]
      }
    };
  },
  computed: {
    ...mapState("user", {
      loginusername: state => state.loginusername
    }),
    ...mapState("login", ["guesscount"]),
    ...mapState("app", ["appname", "username", "userid", "powercode", "token"]),
    ...mapGetters("login", {
      statuscode: "statuscode",
      statusnote: "statusnote",
      getStatus: "getStatus"
    })
  },
  methods: {
    validateUsername(rule, value, callback) {
      if (value.trim().length == 0) {
        callback("用户名不能为空");
      }
    },
    validateUserpassword(rule, value, callback) {
      let inputvalue = value.trim();
      let msg = "";
      if (inputvalue.length == 0) this.errmsg = "密码不能为空";
      else if (inputvalue.length < 8) this.errmsg = "密码长度错误";
      if (this.errmsg.length) callback(this.errmsg);
    },
    onsubmit() {
      console.log("提交到服务器");
    },
    queryword() {
      let url = "http://192.168.124.23:3000/query/compress";
      let vm = this;
      console.log(this.axios);
      this.axios.get(url).then(function(res) {
        console.log(res);
      });
    },
    checkUserObj() {
      let msg = "";
      if (this.loginForm.userpassword.length < 8) msg = "密码长度太短";
      if (this.loginForm.userpassword == 0) msg = "密码不能为空";
      if (this.loginForm.username.length == 0) msg = "用户名不能为空";
      return msg;
    },
    temp() {
      let vm = this;
      const url = "/trylogin";
      let data = this.loginForm;
      const request = this.axios.create({
        baseURL: "http://192.168.124.23:3000",
        timeout: 5000
      });
      request.interceptors.request.use(config => {
        const token = jwt.sign({ name: "Tokken" }, "sec");
        config.headers.common["Authorization"] = "Bearer " + token;
        return config;
      });
      request({
        url,
        method: "post",
        data: data
      }).then(res => {
        console.log(res);
      });
    },
    setToken() {
      let url = "/trylogin";
      let vm = this;
      post(
        url,
        vm.loginForm,
        (res, err) => {
          if (err) {
            console.log("-----------error------------");
            console.log(err);
          } else {
            console.log(res);
            if (res.data.statuscode == 200) {
              vm.setUserinfo(res.data);
              vm.$router.push({ path: "/home" });
            } else {
              vm.$message({ message: res.data.message });
            }
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    sendToken() {
      let vm = this;
      let msg = this.checkUserObj();
      if (msg.length !== 0) {
        this.$message({ message: msg, type: "error" });
      } else {
        let service = this.axios.create({
          baseURL: "http://192.168.124.23:3000",
          timeout: 2000
        });
        let url = "/trylogin";
        service({
          url,
          method: "post",
          data: vm.loginForm
        })
          .then((res, err) => {
            if (err) {
              console.log("-----------error------------");
              console.log(err);
            } else {
              console.log(res);
              if (res.data.statuscode == 200) {
                vm.setUserinfo(res.data);
                vm.$router.push({ path: "/home" });
              } else {
                vm.$message({ message: res.data.message });
              }
            }
          })
          .catch(err => {
            // vm.$message({ message: err.message, type: "error" });
            console.log(err);
          });
      }
    },
    addNewExplanationItem() {},
    handleLogin() {
      //this.temp();
      //this.queryword();
      this.setToken();
      //console.log(this.$refs.loginForm);
      //this.add(3);
      //this.addaction(2);
      //this.async();
      //   this.pro().then(doc => console.log(doc));
      //   this.$refs.loginForm.validate(valid => {
      //     console.log("--------");
      //     console.log(valid);
      //     console.log(this.$store);
      //   });
    },
    testVuex() {
      console.log(this);
    },
    ...mapMutations("login", {
      add: "increment"
    }),
    ...mapActions("login", {
      addaction: "increment",
      setGuess: "setguesscount",
      async: "incrementAsync",
      pro: "incrementPromise"
    }),
    ...mapActions("app", ["setUserinfo"])
  }
};
</script>

<style scoped>
</style>